/*
 *    Copyright 2010-2013 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.google.code.jbauble.db.mysql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;

import com.google.code.jbauble.db.SqlTransaction;
import com.google.code.jbauble.db.exception.DataAccessException;

public class MysqlTransaction implements SqlTransaction {
	protected MysqlNative sqlNative = null;
	protected Connection connection = null;

	public MysqlTransaction(MysqlNative sn) throws DataAccessException {
		sqlNative = sn;
		connection = sqlNative.getConnection(0);
		try {
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			throw new DataAccessException(e);
		}
	}

	public Connection getConnection(int type) throws DataAccessException {
		return connection;
	}

	public <T> List<T> queryForList(String sql, Object[] objs, Class<T> type)
			throws DataAccessException {
		return sqlNative.queryForList(connection, sql, objs, type);
	}

	public <T> T queryForObject(String sql, Object[] objs, Class<T> type)
			throws DataAccessException {
		return sqlNative.queryForObject(connection, sql, objs, type);
	}

	public Long queryForLong(String sql, Object[] objs)
			throws DataAccessException {
		return sqlNative.queryForLong(connection, sql, objs);
	}

	public int execute(String sql, Object[] objs) throws DataAccessException {
		return sqlNative.execute(connection, sql, objs);
	}

	public Object executeInsert(String sql, Object[] objs)
			throws DataAccessException {
		return sqlNative.executeInsert(connection, sql, objs);
	}

	public SqlTransaction beginTransaction() throws DataAccessException {
		return this;
	}

	public void commit() throws DataAccessException {
		try {
			connection.commit();
		} catch (SQLException e) {
			throw new DataAccessException(e);
		} finally {
			DbUtils.closeQuietly(connection);
		}
	}

	public void rollback() throws DataAccessException {
		try {
			connection.rollback();
		} catch (SQLException e) {
			throw new DataAccessException(e);
		} finally {
			DbUtils.closeQuietly(connection);
		}
	}

}
